﻿using Kjs.Report.Domain.Table;
using Kjs.Report.Infrastructure;
using Kjs.Report.IService;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;
using System.Linq;
namespace Kjs.Report.Service
{
    public class SysRoleService : ISysRoleService
    {
        private readonly IUnitOfWork _unitOfWork;
        private IRepository<D_Sys_Role> _role_repository;
        private IRepository<D_Sys_User> _user_repository;

        public SysRoleService(IUnitOfWork unitOfWork)
        {
            _unitOfWork = unitOfWork;
            _role_repository = _unitOfWork.GetRepository<D_Sys_Role>();
            _user_repository = _unitOfWork.GetRepository<D_Sys_User>();
        }

        #region 公共方法

        public async Task<D_Sys_Role> Get(int id)
        {
            return await _role_repository.GetFirstOrDefaultAsync(x => x.id == id, q => q.OrderBy(d => d.id));
        }

        public async Task<List<D_Sys_Role>> GetList()
        {
            var page = await _role_repository.GetPagedListAsync(pageSize: Const.maxPageSize);
            return page.Items.ToList();
        }

        public async Task<Tuple<IList<D_Sys_Role>, int>> GetPageList(string keyWord, int pageIndex, int pageSize)
        {
            Expression<Func<D_Sys_Role, bool>> predicate = x => true;
            if (!string.IsNullOrEmpty(keyWord))
            {
                predicate = predicate.And(x => x.role_name.Contains(keyWord) || x.description.Contains(keyWord));
            }
            var page = await _role_repository.GetPagedListAsync(predicate: predicate, orderBy: source => source.OrderByDescending(x => x.add_time), pageIndex: pageIndex, pageSize: pageSize);
            return new Tuple<IList<D_Sys_Role>, int>(page.Items, page.TotalCount);
        }

        public async Task<int> Add(D_Sys_Role sysRole)
        {
            await _role_repository.InsertAsync(sysRole);
            return await _unitOfWork.SaveChangesAsync();
        }

        public async Task<int> Update(D_Sys_Role sysRole)
        {
            _role_repository.Update(sysRole);
            return await _unitOfWork.SaveChangesAsync();
        }

        public async Task<int> Delete(D_Sys_Role sysRole)
        {
            _role_repository.Delete(sysRole);
            return await _unitOfWork.SaveChangesAsync();
        }
        #endregion
    }

}
